package nyu.cs3033;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterException;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;


/**
 * <p>This is a code example of Twitter4J Streaming API<br>
 * This code writes 20 tweets to the output file named twitterStreamOutput.txt
 * Execution stops once 20 tweets are received.
 * </p>
 *
 */
public class TwitterStreaming {


	public static void main(String[] args) throws TwitterException, IOException{
		StatusListener listener = new StatusListener(){

			//Number of tweets to be written in file.
			int tweetCount = 20;
			String fileOutput = "";

			public void onStatus(Status status) {
				
				String tweet = status.getUser().getName() + " : " + status.getText();
				System.out.println(tweet);
				
				//Appends the tweets to the finalOutput string
				fileOutput += tweet + "\n";
				//Decrements the tweetLimit;
				tweetCount--;
				
				if(tweetCount == 0){
					
					FileWriter fileWriter = null;
					BufferedWriter out = null;
					
					try{
						fileWriter = new FileWriter("./results/twitterStreamOutput.txt");
						out =  new BufferedWriter(fileWriter);
						out.write(fileOutput);
					}catch(IOException ioe){
						System.err.println("Error : "+ioe.getMessage());
					}finally{
						try {
							if(out != null)
								out.close();
							if(fileWriter != null)
								fileWriter.close();
						} catch (IOException e) {
							System.err.println("Error : "+e.getMessage());
						}
					}
					
					//Stops the execution
					System.exit(1);
				}
			}
			
			public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
			public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
			public void onException(Exception ex) {
				ex.printStackTrace();
			}
			@Override
			public void onScrubGeo(long arg0, long arg1) {}
			@Override
			public void onStallWarning(StallWarning arg0) {}
		};

		TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
		twitterStream.addListener(listener);
		twitterStream.sample();
	}

}
